<?php
class Admin
{
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth)
    {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 添加管理员 (需要超级管理员权限)
     * @method POST
     * @route /admin/add
     */
    public function add(): void
    {
        $this->auth->checkSuperAdmin();

        $data = json_decode(file_get_contents('php://input'), true);
        $username = $data['username'] ?? '';
        $password = $data['password'] ?? '';
        $permission = $data['permission'] ?? 'admin';

        if (empty($username) || empty($password)) {
            throw new Exception("用户名和密码不能为空", 400);
        }

        // 验证权限类型
        if (!in_array($permission, ['admin', 'superadmin'])) {
            throw new Exception("权限类型错误", 400);
        }

        // 检查用户名是否已存在
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE username = :username LIMIT 1");
        $stmt->execute([':username' => $username]);
        if ($stmt->fetch()) {
            throw new Exception("用户名已存在", 409);
        }

        // 验证密码强度
        if (strlen($password) < 8 || !preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $password)) {
            throw new Exception("密码必须至少8位且包含字母和数字", 400);
        }

        // 加密密码
        $hashedPassword = Security::hashPassword($password);
        $time = time();

        // 插入新管理员
        $stmt = $this->conn->prepare("
            INSERT INTO users (
                username, password, permission, status, create_time, sub_mobile
            ) VALUES (
                :username, :password, :permission, 1, :create_time, :sub_mobile
            )
        ");

        // 生成唯一的sub_mobile值
        $subMobile = 'admin_' . time() . '_' . rand(1000, 9999);
        
        if (!$stmt->execute([
            ':username' => $username,
            ':password' => $hashedPassword,
            ':permission' => $permission,
            ':create_time' => $time,
            ':sub_mobile' => $subMobile
        ])) {
            throw new Exception("添加管理员失败", 500);
        }

        $newAdminId = $this->conn->lastInsertId();

        echo json_encode([
            'code' => 200,
            'msg' => '管理员添加成功',
            'data' => [
                'id' => $newAdminId,
                'username' => $username,
                'permission' => $permission
            ]
        ]);
    }

    /**
     * 修改用户权限 (需要超级管理员权限)
     * @method POST
     * @route /admin/changePermission
     */
    public function changePermission(): void
    {
        $this->auth->checkSuperAdmin();

        $data = json_decode(file_get_contents('php://input'), true);
        $userId = $data['user_id'] ?? 0;
        $permission = $data['permission'] ?? 'member';

        if (empty($userId)) {
            throw new Exception("用户ID不能为空", 400);
        }

        // 验证权限类型
        $allowedPermissions = ['member', 'admin', 'superadmin'];
        if (!in_array($permission, $allowedPermissions)) {
            throw new Exception("权限类型错误", 400);
        }

        // 检查用户是否存在
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $userId]);
        if (!$stmt->fetch()) {
            throw new Exception("用户不存在", 404);
        }

        // 更新权限
        $stmt = $this->conn->prepare("
            UPDATE users SET permission = :permission WHERE id = :id
        ");

        if (!$stmt->execute([
            ':permission' => $permission,
            ':id' => $userId
        ])) {
            throw new Exception("修改权限失败", 500);
        }

        echo json_encode([
            'code' => 200,
            'msg' => '权限修改成功'
        ]);
    }

    /**
     * 获取当前用户信息
     * @method GET
     */
    public function info(): void
    {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $stmt = $this->conn->prepare("
            SELECT u.id, u.username, u.mobile, u.real_name, u.position, u.create_time, 
                   u.last_login_time, u.permission, c.id as company_id, c.name as company_name
            FROM users u
            LEFT JOIN companies c ON u.company_id = c.id
            WHERE u.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            throw new Exception("用户不存在", 404);
        }

        // 返回用户信息
        echo json_encode([
            'code' => 200,
            'data' => $user
        ]);
    }
    /**
     * 管理员登录
     * @method POST
     * @route /admin/login
     */
    public function login(): void
    {
        $data = json_decode(file_get_contents('php://input'), true);

        if (empty($data['username']) || empty($data['password'])) {
            throw new Exception("请输入用户名和密码", 400);
        }

        // 查询用户信息，允许管理员、超级管理员和超管助理登录
        $stmt = $this->conn->prepare(
            "
            SELECT id, username, password, permission, status, is_owner
            FROM users
            WHERE username = :username 
            AND permission IN ( 'superadmin', 'assistant')
            LIMIT 1
            "
        );
        $stmt->execute([':username' => $data['username']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            throw new Exception("管理员账号不存在", 401);
        }

        // 验证密码
        if (!Security::verifyPassword($data['password'], $user['password'])) {
            throw new Exception("用户名或密码错误", 401);
        }

        // 检查用户状态
        if ($user['status'] != 1) {
            throw new Exception("账号已被禁用，请联系超级管理员", 403);
        }

        // 生成新Token
        $token = Security::generateToken($user['id']);
        $tokenExpire = time() + TOKEN_EXPIRE;

        // 更新用户Token和最后登录时间
        $stmt = $this->conn->prepare("
            UPDATE users
            SET 
                token = :token,
                token_expire = :token_expire,
                last_login_time = :last_login_time
            WHERE id = :id
        ");
        $stmt->execute([
            ':token' => $token,
            ':token_expire' => $tokenExpire,
            ':last_login_time' => time(),
            ':id' => $user['id']
        ]);

        // 返回登录成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'token_expire' => $tokenExpire,
                'permission' => $user['permission'],
                'is_owner' => $user['is_owner']
            ]
        ]);
    }

    /**
     * 获取管理员列表 (需要管理员权限)
     * @method GET
     * @route /admin/list
     */
    public function list(): void
    {
        $this->auth->checkAdmin();

        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(50, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = ["permission IN ('admin', 'superadmin', 'assistant')"];
        $params = [];

        if (!empty($_GET['keyword'])) {
            $keyword = '%' . $_GET['keyword'] . '%';
            $where[] = "(username LIKE :keyword OR real_name LIKE :keyword OR mobile LIKE :keyword)";
            $params[':keyword'] = $keyword;
        }

        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        // 查询总数
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM users {$whereClause}");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();

        // 查询数据
        $stmt = $this->conn->prepare("
            SELECT id, username, company, mobile, real_name, position, status, 
                   permission, create_time, last_login_time
            FROM users
            {$whereClause}
            ORDER BY id DESC
            LIMIT :offset, :limit
        ");
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);

        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }

        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }
}
